package com.vdong.rms.service.impl;

import com.vdong.rms.common.exception.ProcessException;
import com.vdong.rms.entity.domain.ServiceDO;
import com.vdong.rms.entity.domain.UserDO;
import com.vdong.rms.entity.mo.*;
import com.vdong.rms.entity.mo.System;
import com.vdong.rms.entity.parameter.ValidatePO;
import com.vdong.rms.entity.template.UserTokenTM;
import com.vdong.rms.entity.validate.GroupRequired;
import com.vdong.rms.repository.dao.*;
import com.vdong.rms.repository.operation.UserTokenTMOperation;
import com.vdong.rms.service.IdentityVerificationService;
import org.apache.commons.collections.CollectionUtils;
import org.lamb.framework.common.util.CopyUtil;
import org.lamb.framework.common.util.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

import static com.vdong.rms.common.enums.FoundationPropertyEnum.T_SERVICE_ANY;
import static com.vdong.rms.common.enums.FoundationPropertyEnum.T_SERVICE_AUTC;
import static com.vdong.rms.common.enums.FoundationPropertyEnum.T_SERVICE_AUTZ;
import static com.vdong.rms.common.enums.ProcessExceptionEnum.*;
import static com.vdong.rms.common.enums.RedisTMKeyEnum.USER_TOKEN;


/**
 * @description: 身份验证
 * @author: Mr.WangGang
 * @create: 2018-10-17 下午 12:31
 **/
@Service
public class IdentityVerificationServiceImpl implements IdentityVerificationService {

    @Resource
    private UserTokenTMOperation userTokenTMOperation;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SystemMapper systemMapper;

    @Autowired
    private SystemServiceMapper systemServiceMapper;

    @Autowired
    private RmsServiceMapper rmsServiceMapper;

    @Override
    public void validate(ValidatePO validatePO) {
        ValidatorUtil.validate(validatePO);

        RmsServiceExample rmsServiceExample = new RmsServiceExample();
        rmsServiceExample.createCriteria().andServiceCodeEqualTo(validatePO.getServiceCode());
        List<RmsService> serviceList = rmsServiceMapper.selectByExample(rmsServiceExample);
        if (CollectionUtils.isEmpty(serviceList)) {
            throw new ProcessException(EB00000003);
        }

        //ServiceDO serviceDO = serviceDORepository.findByServiceCode(validatePO.getServiceCode()).orElseThrow(() -> new ProcessException(EB00000003));
        RmsService rmsService = serviceList.get(0);
        Short serviceStrategy = rmsService.getServiceStrategy();

        ServiceDO serviceDO = CopyUtil.copyObject(rmsService, new ServiceDO());

        if (T_SERVICE_ANY.getType().equals(serviceStrategy)) {
            //任何人都可以访问
            return;
        } else if (T_SERVICE_AUTC.getType().equals(serviceStrategy)) {
            //需要认证
            UserDO userDO = autc(validatePO);
            legitimateRequestUSS(userDO, serviceDO);
            return;
        } else if (T_SERVICE_AUTZ.getType().equals(serviceStrategy)) {
            //需要授权
            UserDO userDO = autc(validatePO);
            legitimateRequestUSS(userDO, serviceDO);
            autz(userDO, serviceDO);
            return;
        } else {
            throw new ProcessException(EB00000004);
        }
    }

    //认证
    private UserDO autc(ValidatePO validatePO) {
        ValidatorUtil.validate(validatePO, GroupRequired.class);
        UserTokenTM userTokenTM = Optional.ofNullable(userTokenTMOperation.getObject(
                USER_TOKEN.getKey() + validatePO.getAccessToken())).orElseThrow(() -> new ProcessException(EB00000000));
        User user = userMapper.selectByPrimaryKey(userTokenTM.getUserId());
        if (user == null) {
            throw new ProcessException(EB00000000);
        }
        UserDO userDO = new UserDO();
        CopyUtil.copyObject(userDO, user);
        return userDO;
    }

    //授权
    private void autz(UserDO userDO, ServiceDO serviceDO) {

        List<RmsService> serviceList = rmsServiceMapper.selectServiceByUserId(userDO.getUserId());

        if (CollectionUtils.isEmpty(serviceList)) {
            throw new ProcessException(EB00000005);
        }

        if (serviceList.stream().noneMatch(e -> serviceDO.getServiceId().compareTo(e.getServiceId()) == 0)) {
            throw new ProcessException(EB00000005);
        }

        /*List<ServiceDO> services = serviceDORepository.findServiceByUserId(userDO.getUserId()).orElseThrow(() -> new ProcessException(EB00000005));
        if (services.stream().noneMatch(e -> serviceDO.getServiceId().compareTo(e.getServiceId()) == 0)) {
            throw new ProcessException(EB00000005);
        }*/
    }

    //合法的用户系统服务之间关系
    private void legitimateRequestUSS(UserDO userDO, ServiceDO serviceDO) {
        System system = systemMapper.selectByPrimaryKey(userDO.getSystemId());
        if (system == null) {
            throw new ProcessException(EB00000001);
        }

        SystemServiceExample example = new SystemServiceExample();
        example.createCriteria().andServiceIdEqualTo(serviceDO.getServiceId());
        List<SystemService> systemServiceList = systemServiceMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(systemServiceList)) {
            throw new ProcessException(EB00000002);
        }

        /*SystemService systemService = systemServiceMapper.selectByPrimaryKey(serviceDO.getServiceId());
        if (systemService == null) {
            throw new ProcessException(EB00000002);
        }*/
    }
}
